package com.ms.dsq_english.views;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;


import com.ms.dsq_english.R;
import com.ms.dsq_english.base.BaseApplication;
import com.ms.dsq_english.model.BanBean;
import com.ms.dsq_english.service.DownloadService;
import com.ms.dsq_english.utils.CustomToast;
import com.ms.dsq_english.utils.NetSpeed;
import com.ms.dsq_english.utils.NetSpeedTimer;
import com.ms.dsq_english.utils.NumUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ms.dsq_english.utils.FileSizeUtils.formatFileSize;


public class UpdateDialog
{
    private BaseApplication application;

    private int totalSize = 0;

    private TextView tvProgress, tvUpdate;
    private ProgressBar pb;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler()
    {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);

            switch (msg.what)
            {
                case 1:
                {
//                    tvProgress.setText(formatFileSize(application.currentSize) + "/" + formatFileSize(totalSize));


                    pb.setProgress(application.currentSize);
                    Log.i("1000", "handleMessage: "+application.currentSize/totalSize);
                    Log.i("1000", "handleMessageddd: "+application.currentSize);
                    Log.i("1000", "handleMessaged: "+totalSize);
                    NumUtils numUtils =   new NumUtils();
                    double num = numUtils.divide(application.currentSize,totalSize,2);
                    double baifen =  num*100;
                    int  zong = (int) baifen;
                    baifenbi.setText(zong+"%");
                    break;
                }
                default:
                    break;
            }
        }
    };

    private Runnable runnable = new Runnable()
    {
        @Override
        public void run()
        {
            handler.sendEmptyMessage(1);

            if (application.currentSize < totalSize)
            {
                handler.postDelayed(runnable, 1000);

//                LogUtils.showLog("Download", "run currentSize=" + application.currentSize);
//                LogUtils.showLog("Download", "run totalSize=" + totalSize);
            }
            else
            {
                tvUpdate.setClickable(true);
                tvUpdate.setText("前往安装");

//                LogUtils.showLog("Download", "run 下载完成");
//                LogUtils.showLog("Download", "run currentSize=" + application.currentSize);
//                LogUtils.showLog("Download", "run totalSize=" + totalSize);
            }
        }
    };
    private TextView dia_update_tv_wang;
    private TextView baifenbi;

    @SuppressLint("SetTextI18n")
    public void showUpdateDialog(final Context context, final BanBean info)
    {
        String num= getNumeric(info.getSize());
        application = (BaseApplication) context.getApplicationContext();
        totalSize = Integer.parseInt(num);

        final Dialog dialog = new Dialog(context, R.style.FullscreenDialogTheme_Center);
        dialog.setContentView(R.layout.pop_dateup);
        dialog.setCancelable(false);
        TextView tvContent = dialog.findViewById(R.id.dia_update_tv_content);
        tvUpdate = dialog.findViewById(R.id.dia_update_tv_update);
        TextView pop_text = dialog.findViewById(R.id.pop_text);
        pb = dialog.findViewById(R.id.dia_update_pb);
        dia_update_tv_wang = dialog.findViewById(R.id.dia_update_tv_wang);
        baifenbi = dialog.findViewById(R.id.baifenbi);
        pb.setVisibility(View.GONE);
        baifenbi.setVisibility(View.GONE);
        tvContent.setText(info.getUpgrade_tips());
        tvContent.setMovementMethod(ScrollingMovementMethod.getInstance());
        pb.setMax(totalSize);
        tvUpdate.setOnClickListener(v -> {
            tvUpdate.setClickable(false);
            tvUpdate.setVisibility(View.GONE);
            pop_text.setText("正在下载");
            tvContent.setText("请稍候…");
            pb.setVisibility(View.VISIBLE);
            baifenbi.setVisibility(View.VISIBLE);
            initNewWork(context);
            Intent it = new Intent(context, DownloadService.class);
            it.putExtra("url", info.getApk_url());
            it.putExtra("version", info.getNew_version());
            it.putExtra("totalSize", num);
            context.startService(it);
            CustomToast.showShortToast(context, "为您后台下载中，下载后将提示安装");
            handler.postDelayed(runnable, 1000);
        });

        dialog.show();
    }

    private void initNewWork(Context mContext) {
        //创建NetSpeedTimer实例
        NetSpeedTimer mNetSpeedTimer = new NetSpeedTimer(mContext, new NetSpeed(), mHandler).setDelayTime(1000).setPeriodTime(2000);
        //在想要开始执行的地方调用该段代码
        mNetSpeedTimer.startSpeedTimer();
    }


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == NetSpeedTimer.NET_SPEED_TIMER_DEFAULT){
                String speed = (String) msg.obj;
                String num= getNumeric(speed);
                 int dsd = Integer.parseInt(num);
                 int numb =  dsd*1024;
                dia_update_tv_wang.setText("本次更新"+formatFileSize(totalSize)+"，速度"+formatFileSize(numb)+"/s");
            }
        }
    };

    public static String getNumeric(String str) {
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

}
